package com.shensi.adminCollect.service.station.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shensi.common.core.domain.entity.SysUser;
import com.shensi.common.core.exception.CustomException;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.utils.StringUtils;
import com.shensi.adminCollect.domain.station.WxMessageTemplate;
import com.shensi.adminCollect.domain.station.form.WxMessageTemplateForm;
import com.shensi.adminCollect.domain.station.form.WxMessageTemplateQueryForm;
import com.shensi.adminCollect.domain.station.vo.WxMessageTemplateQueryVo;
import com.shensi.adminCollect.domain.station.vo.WxMessageTemplateVo;
import com.shensi.adminCollect.mapper.station.WxMessageTemplateMapper;
import com.shensi.adminCollect.service.station.GzhMenuService;
import com.shensi.adminCollect.service.station.WxMessageTemplateService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class WxMessageTemplateServiceImpl implements WxMessageTemplateService {

    @Autowired
    private WxMessageTemplateMapper wxMessageTemplateMapper;
    @Autowired
    private GzhMenuService gzhMenuService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertWxMessageTemplate(WxMessageTemplateForm wxMessageTemplateForm) {
        operaPermission(wxMessageTemplateForm.getEnterpriseId());

        wxMessageTemplateForm.getWxTemplateContentList().forEach(wxTemplateContent -> {
            WxMessageTemplate wxMessageTemplate = new WxMessageTemplate();
//            if (StringUtils.isEmpty(wxTemplateContent.getTemplateId())) throw new CustomException("模板id不能为空");
            if (ObjectUtils.isEmpty(wxTemplateContent.getTemplateType())) throw new CustomException("模板类型不能为空");

            BeanUtils.copyProperties(wxTemplateContent, wxMessageTemplate);
            wxMessageTemplate.setEnterpriseId(wxMessageTemplateForm.getEnterpriseId());
            wxMessageTemplate.setPushChannel(wxMessageTemplateForm.getPushChannel());
            wxMessageTemplate.setCreatedBy(SecurityUtils.getUsername());
            wxMessageTemplate.setUpdatedBy(SecurityUtils.getUsername());
            try {
                wxMessageTemplateMapper.insertWxMessageTemplate(wxMessageTemplate);
            } catch (DuplicateKeyException duplicateKeyException) {
                throw new CustomException("该油企已存在记录！");
            }
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateWxMessageTemplate(WxMessageTemplateForm wxMessageTemplateForm) {
        operaPermission(wxMessageTemplateForm.getEnterpriseId());

        for (WxMessageTemplateForm.WxTemplateContent wxTemplateContent : wxMessageTemplateForm.getWxTemplateContentList()) {
            if (ObjectUtils.isEmpty(wxTemplateContent.getId())) {
                WxMessageTemplate result = wxMessageTemplateMapper.getByEnterpriseIdAndType(wxMessageTemplateForm.getEnterpriseId(), wxTemplateContent.getTemplateType());
                if (ObjectUtils.isNotEmpty(result)) throw new CustomException("模板id不能为空");

                WxMessageTemplate wxMessageTemplate = new WxMessageTemplate();
                BeanUtils.copyProperties(wxTemplateContent, wxMessageTemplate);
                wxMessageTemplate.setEnterpriseId(wxMessageTemplateForm.getEnterpriseId());
                wxMessageTemplate.setPushChannel(wxMessageTemplateForm.getPushChannel());
                wxMessageTemplate.setCreatedBy(SecurityUtils.getUsername());
                wxMessageTemplate.setUpdatedBy(SecurityUtils.getUsername());
                wxMessageTemplateMapper.insertWxMessageTemplate(wxMessageTemplate);
                continue;
            }

            WxMessageTemplate wxMessageTemplate = new WxMessageTemplate();
            BeanUtils.copyProperties(wxTemplateContent, wxMessageTemplate);
            wxMessageTemplate.setEnterpriseId(wxMessageTemplateForm.getEnterpriseId());
            wxMessageTemplate.setTemplateId(wxTemplateContent.getTemplateId());
            wxMessageTemplate.setPushChannel(wxMessageTemplateForm.getPushChannel());
            wxMessageTemplate.setUpdatedBy(SecurityUtils.getUsername());
            wxMessageTemplate.setUpdatedTime(new Date());
            try {
                wxMessageTemplateMapper.updateWxMessageTemplate(wxMessageTemplate);
            } catch (DuplicateKeyException duplicateKeyException) {
                throw new CustomException("该油企已存在记录！");
            }
        }
    }

    @Override
    public WxMessageTemplateVo selectWxMessageTemplateById(Long enterpriseId) {
        return wxMessageTemplateMapper.getByEnterpriseId(enterpriseId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteWxMessageTemplate(String enterpriseIds) {
        List<String> enterpriseIdList = Arrays.asList(enterpriseIds.split(","));
        enterpriseIdList.forEach(enterpriseId -> {
            operaPermission(Long.valueOf(enterpriseId));
            WxMessageTemplateVo wxMessageTemplateVo = wxMessageTemplateMapper.getByEnterpriseId(Long.valueOf(enterpriseId));
            if(ObjectUtils.isEmpty(wxMessageTemplateVo) || ObjectUtils.isEmpty(wxMessageTemplateVo.getWxTemplateContentList())) return;

            wxMessageTemplateVo.getWxTemplateContentList().forEach(wxTemplateContentVo -> {
                WxMessageTemplate wxMessageTemplate = new WxMessageTemplate();
                wxMessageTemplate.setId(wxTemplateContentVo.getId());
                wxMessageTemplate.setUpdatedBy(SecurityUtils.getUsername());
                wxMessageTemplate.setUpdatedTime(new Date());
                wxMessageTemplate.setDel(System.currentTimeMillis());
                wxMessageTemplateMapper.updateWxMessageTemplate(wxMessageTemplate);
            });
        });
    }

    @Override
    public List<WxMessageTemplateQueryVo> pageWxMessageTemplate(WxMessageTemplateQueryForm queryForm) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String userLevel = user.getUserLevel();
        if (StringUtils.isNotEmpty(userLevel) && ObjectUtils.notEqual(userLevel, "0")) {
            queryForm.setEnterpriseId(user.getEnterpriseId());
        }

        return wxMessageTemplateMapper.pageWxMessageTemplate(queryForm);
    }

    /**
     * 判断当前登录用户是否拥有操作权限
     * @param enterpriseId 油企id
     */
    private void operaPermission(Long enterpriseId) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String userLevel = user.getUserLevel();
        if (StringUtils.isNotEmpty(userLevel) && userLevel.equals("0"))
            throw new CustomException("没有权限操作微信模板，请使用油企账号操作！");
        if (StringUtils.isNotEmpty(userLevel) && userLevel.equals("1") && ObjectUtils.notEqual(user.getEnterpriseId(), enterpriseId)) // 1:油企
            throw new CustomException("没有权限操作！");
        if (StringUtils.isNotEmpty(userLevel) && userLevel.equals("2")) // 2:油站
            throw new CustomException("没有权限操作微信模板，请使用油企账号操作！");
    }

    @Override
    public boolean checkWxMessageTemplate(WxMessageTemplateForm wxMessageTemplateForm) {

        boolean returnVal = false;
        if (wxMessageTemplateForm.getPushChannel().equals(1)) {
            if (wxMessageTemplateForm.getWxTemplateContentList().size() > 0) {
                String templateId = wxMessageTemplateForm.getWxTemplateContentList().get(0).getTemplateId();
                Long enterpriseId = wxMessageTemplateForm.getEnterpriseId();
                Integer templateType = wxMessageTemplateForm.getWxTemplateContentList().get(0).getTemplateType();
                if (StringUtils.isNotEmpty(templateId) && Objects.nonNull(enterpriseId)&& Objects.nonNull(templateType)) {
                    String key = "wx:template:" + enterpriseId;

                    List<String> listWxMessageTemplate = new ArrayList<>();
//                    List<Map> listWxMessageTemplateMap = new ArrayList<>();

                    if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
                        listWxMessageTemplate = redisTemplate.opsForList().range(key, 0, -1);
                    } else {
                        String gzhToken = gzhMenuService.getGzhToken(enterpriseId);

                        JSONObject allPrivateTemplate = WeiXinUserUtil.getAllPrivateTemplate(gzhToken);
                        JSONArray jsonArray = JSONObject.parseArray(allPrivateTemplate.get("template_list").toString());
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject = JSONObject.parseObject(jsonArray.get(i).toString());
                            HashMap<String, String> objectObjectHashMap = new HashMap<>();
                            objectObjectHashMap.put(jsonObject.get("title").toString(),jsonObject.get("template_id").toString());

                            listWxMessageTemplate.add(JSONObject.toJSONString(objectObjectHashMap));
                        }
                        redisTemplate.opsForList().rightPushAll(key, listWxMessageTemplate);
                        redisTemplate.expire(key, 1, TimeUnit.MINUTES);

                    }
/*模板类型：1.加油成功通知；2.积分变动通知；3.充值成功通知；4.商品调价通知；5.订单完成通知（优惠券发放通知）*/
                    returnVal = isReturnVal(returnVal, templateId, templateType, listWxMessageTemplate);
                }
            }
        }
        return returnVal;
    }

    private boolean isReturnVal(boolean returnVal, String templateId, Integer templateType, List<String> listWxMessageTemplate) {
        if (listWxMessageTemplate != null) {
            returnVal = listWxMessageTemplate.stream().anyMatch(val -> {
                JSONObject jsonObject = JSONObject.parseObject(val);
                switch (templateType){
                    case 1:
                        return templateId.equals(jsonObject.get("加油站消费成功通知"));//1
                    case 3:
                        return templateId.equals(jsonObject.get("余额充值成功通知"));//1
                    case 4:
                        return templateId.equals(jsonObject.get("加油卡圈存圈提提醒"));//1
                    case 5:
                    case 6:
                        return templateId.equals(jsonObject.get("订单完成通知"));//1
                    case 7:
                        return templateId.equals(jsonObject.get("退款成功通知"));//1
                    case 8:
                        return templateId.equals(jsonObject.get("交易成功通知"));//1
                    case 9:
                        return templateId.equals(jsonObject.get("订单创建成功通知"));//1
                    case 10:
                        return templateId.equals(jsonObject.get("月账单通知"));
                    default:
                        return false;
                }
            });
        }
        return returnVal;
    }
}
